package com.runmi.webchat.aftersale.web.shop.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.StringUtil;
import com.runmi.webchat.aftersale.common.result.Result;
import com.runmi.webchat.aftersale.common.result.ResultFactory;
import com.runmi.webchat.aftersale.config.WxConfig;
import com.runmi.webchat.aftersale.dbcore.entity.ShopInfo;
import com.runmi.webchat.aftersale.dbcore.mapper.ShopInfoMapper;
import com.runmi.webchat.aftersale.util.Constants;
import com.runmi.webchat.aftersale.web.base.BaseController;
import com.runmi.webchat.aftersale.web.set.model.RoleIndex;
import com.runmi.webchat.aftersale.web.set.model.UserEdit;
import com.runmi.webchat.aftersale.web.set.service.RoleService;
import com.runmi.webchat.aftersale.web.shop.service.ShopManageService;
import com.runmi.webchat.aftersale.web.shop.vo.ShopManageEditReqVo;
import com.runmi.webchat.aftersale.web.shop.vo.ShopManageIndexReqVo;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Controller
@RequestMapping(value = "/admin/shop")
public class ShopManageController extends BaseController{

	@Autowired
	private ShopManageService shopManageService;
	
	@Autowired
	private ShopInfoMapper shopInfoMapper;
	
	@Autowired
	private WxConfig wxConfig;
	
	
	@RequestMapping(value = "/index")
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response,ShopManageIndexReqVo model){
		ModelAndView mav = new ModelAndView("/shop/index");		
		shopManageService.index(model);
    	mav.addObject("model", model);
        return mav;
		//return "/customer/Customer/seach";
	}
	

	@RequestMapping(value = "/edit")
	public ModelAndView edit(HttpServletRequest request,HttpServletResponse response,ShopManageEditReqVo model){
		//model.setUserId(this.getUserId(request, response));
		ModelAndView mav = new ModelAndView("/shop/edit");		
		shopManageService.edit(model);
    	mav.addObject("model",model);
        return mav;
		//return "/customer/Customer/seach";
	}

	
	@PostMapping(value = "/saveShop")
	@ResponseBody
	public Result saveShop(
			HttpServletRequest request,HttpServletResponse response,
			Integer shopId,
			String shopCode,
			String shopName,			
			Integer provinceId,
			Integer cityId,
			Integer areaId,
			String address,
			String contactName,
			String contactMobile){
		return shopManageService.saveShop(
				shopId, shopCode, shopName, 
				provinceId, cityId, areaId, address,contactName,contactMobile,
				this.getUserInfo(request, response));
		
	}
	
	@PostMapping(value = "/changeStatus")
	@ResponseBody
	public Map<String,String> changeStatus(HttpServletRequest request,HttpServletResponse response,Integer shopId,Byte opType){
	
		Map<String,String> result=shopManageService.changeStatus(this.getUserInfo(request, response),shopId,opType);
		return result;
	}
	
	@PostMapping(value = "/del")
	@ResponseBody
	public Result del(HttpServletRequest request,HttpServletResponse response,Integer shopId){
	
		Result result=shopManageService.del(this.getUserInfo(request, response),shopId);
		return result;
	}
	
	@PostMapping(value = "/createCode")
	@ResponseBody
	public Result createCode(HttpServletRequest request,HttpServletResponse response,String shopId,String type){
		if(null==shopId){
			return ResultFactory.getResultFail("店铺ID为空");
		}
		String fileName=getminiqrQr(shopId,type,wxConfig.getAccessToken());
		if(StringUtil.isNotEmpty(fileName)){
			String url="/common/img/show?imageName=" + fileName;
			System.out.println(request.getServerPort());
			System.out.println(request.getRemoteAddr());
			System.out.println(request.getContextPath());
			int port =request.getServerPort();
			if(port==80){
				url="://"+request.getServerName() + request.getContextPath() +  url;
			}else{
				url="://"+request.getServerName() + ":" + port + "" + request.getContextPath() +  url;
			}
			ShopInfo shopInfo= shopInfoMapper.selectByPrimaryKey(Integer.parseInt(shopId));
			if(null!=shopInfo){
				ShopInfo record=new ShopInfo();
				record.setId(shopInfo.getId());
				if(type.equals("1")){
					record.setCodeUrl1(url);;
				}
				if(type.equals("2")){
					record.setCodeUrl2(url);;
				}
				if(type.equals("3")){
					record.setCodeUrl3(url);;
				}
				shopInfoMapper.updateByPrimaryKeySelective(record);
			}			
		}
		
		return ResultFactory.getResultSuccess();
	}
	
	public String getminiqrQr(String shopId, String type, String accessToken) {
		String filePath="";
	        RestTemplate rest = new RestTemplate();
	        InputStream inputStream = null;
	        OutputStream outputStream = null;
	        try {
	            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
	            Map<String,Object> param = new HashMap<>();
	            param.put("scene", shopId + "&type="+type );
//	            String path="pages/apply/apply";
//	            if(type.equals("2")){
//	            	path="pages/issues/issues";
//	            }
	            param.put("page", "pages/index/index");
	            param.put("width", 430);
//	            param.put("auto_color", false);
//	            Map<String,Object> line_color = new HashMap<>();
//	            line_color.put("r", 0);
//	            line_color.put("g", 0);
//	            line_color.put("b", 0);
//	            param.put("line_color", line_color);
	            //LOG.info("调用生成微信URL接口传参:" + param);
	            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
	            HttpEntity requestEntity = new HttpEntity(param, headers);
	            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
	            //LOG.info("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
	            byte[] result = entity.getBody();
	           // LOG.info(Base64.encodeBase64String(result));
	            inputStream = new ByteArrayInputStream(result);
	            
	            String pathFile= Constants.SYSTEM_IMAGE_FILE_PATH; 
	            File targetFile = new File(pathFile);
		        if(!targetFile.exists()){
		        	targetFile.mkdirs();
		        }
	            File file = new File(pathFile + "/"+shopId +"_"+ type +  ".png");
	            if (!file.exists()){
	                file.createNewFile();
	            }
	            outputStream = new FileOutputStream(file);
	            int len = 0;
	            byte[] buf = new byte[1024];
	            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
	                outputStream.write(buf, 0, len);
	            }
	            outputStream.flush();
	            filePath=shopId +"_" + type +  ".png";
	        } catch (Exception e) {
	            //LOG.error("调用小程序生成微信永久小程序码URL接口异常",e);
	        } finally {
	            if(inputStream != null){
	                try {
	                    inputStream.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            if(outputStream != null){
	                try {
	                    outputStream.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	        return filePath;    
	    }
}
